#include<iostream>
#include<unistd.h>
#include<assert.h>
#include<string>
#include<cstdio>
#include<cstring>
#include<sys/wait.h>
#include<sys/wait.h>
using namespace std;
int main()
{   
    int pipefd[2]={0};
    
    int n = pipe(pipefd);
    assert(n!=-1);

    (void)n;
#ifdef DEBUG
    cout<<"pipefd[1]"<<pipefd[1]<<endl;
    cout<<"pipefd[0]"<<pipefd[0]<<endl;
#endif

    pid_t id = fork();
    assert(id!=-1);
    if(id == 0)//子进程：读取，关闭写 
    {
        close(pipefd[1]);
        char buffer[64]={0};
        int count=0;
        while(1)
        {
            ssize_t s = read(pipefd[0],buffer,sizeof(buffer)-1);
            if(s>0)
            {
                buffer[s]=0;
                cout<<"子进程pid:"<<getpid()<<"得到信息："<<"_父进程发送信息："<<buffer<<endl;
                count++;
                if(count>=5)
                {
                    cout<<"读取结束,读取流关闭"<<endl;
                    break;
                }
                
            }
            else if(s==0)
            {
                cout<<"父进程停止输入，子进程停止读取"<<endl;
                break;
            }
        }    
        close(pipefd[0]);


        exit(0);
    }

    close(pipefd[0]);//父进程：写入，关闭读取流
    string message = "父进程写入信息:";
    int count = 0;
    char send_buffer[64];
    while(1)
    {
        snprintf(send_buffer,sizeof(send_buffer),"%s[%d] : %d",message.c_str(),getpid(),count);
        count++;

        write(pipefd[1],send_buffer,strlen(send_buffer));
        sleep(1);
        /*
        if(count>=5)
        {
            cout<<"父进程退出"<<endl;
            break;
        }
        */
    }
    close(pipefd[1]);
    int status = 0;
    pid_t ret = waitpid(id,&status,0);
    assert(ret>0);
    (void)ret;
    
    return 0;
}
